<?php

namespace Swof\Server\Http;

use Swof\Http\HttpRequest;
use Swof\Server\Server;
use Swoole\Http\Request as SwoRequest;
use Swoole\Http\Response as SwoResponse;
use Swoole\Http\Server as SwoHttpServer;

class HttpServer extends Server
{
    /**
     * Note: 初始化事件
     *
     * @author: Zhao Zhiqiang
     * @since: 2021/5/11 17:25
     */
    protected function initEvent()
    {
        $this->setEvent('sub', [
            'request' => 'onRequest',
        ]);
    }

    /**
     * Note: 创建 Http 服务器
     *
     * @return mixed|void
     * @author: Zhao Zhiqiang
     * @since: 2021/5/11 17:29
     */
    public function createServer()
    {
        $this->swoServer = new SwoHttpServer(
            config('server.http.host'),
            config('server.http.port')
        );
    }

    public function onRequest(SwoRequest $swoRequest, SwoResponse $swoResponse)
    {
        if ($swoRequest->server['path_info'] == '/favicon.ico'
            || $swoRequest->server['request_uri'] == '/favicon.ico') {
            $swoResponse->status(404);
            $swoResponse->end();
            return;
        }

        $request = HttpRequest::initialize($swoRequest);

        $result = app('router')->dispatchToRoute($request);

        $swoResponse->end("<h1>$result</h1>");
    }
}
